package my.com.sunway.util;

import java.security.*;

public class MD5Util{
 /**
  * @param clearTextID text ID which you wish to hash
  * @return hashed value of clearTextID in byte[] format
  */     
 public static final byte[] generateHash(String clearTextID){
  byte[] buffer = null;
  byte[] digest1 = null;
  MessageDigest algorithm = null;
  
  try{
   buffer = clearTextID.getBytes();
   algorithm = MessageDigest.getInstance("MD5");
   // Generate the digest.
   algorithm.reset();
   algorithm.update(buffer);
   digest1 = algorithm.digest();
  }catch(Exception ex){
   // ignore error, just print out
   System.out.println(ex);
  }finally{
   return digest1;
  }
 }
 
 /**
  * @param clearTextID text ID which you wish to hash
  * @return hashed value of clearTextID in byte[] format
  */     
 public static final int generateHashToInt(String clearTextID){
  return unsignedByteToInt(generateHash(clearTextID));
 }
 
 public static final int unsignedByteToInt(byte[] b){
  int ret = 0;
  for(int i=0; i<b.length; i++){
   ret |= b[i] & 0xFF;
   if(i<(b.length-1)){
    ret <<= 8 * (i + 1);
   }
  }
  return ret;
 }
}
